// Anonymous Functions (匿名函数) 示例
program AnonymousFunctionsExample;

{$mode objfpc}{$H+}

uses
  SysUtils;

type
  // 定义匿名函数类型
  TIntegerFunction = reference to function(a, b: Integer): Integer;
  TSimpleFunction = reference to procedure;

// 使用匿名函数作为参数的高阶函数
function ApplyFunction(a, b: Integer; func: TIntegerFunction): Integer;
begin
  Result := func(a, b);
end;

// 返回匿名函数的函数
function GetMultiplier(factor: Integer): TIntegerFunction;
begin
  Result := function(x, y: Integer): Integer
            begin
              Result := x * y * factor;
            end;
end;

var
  AddFunc, MultiplyFunc: TIntegerFunction;
  SimpleProc: TSimpleFunction;
  Multiplier: TIntegerFunction;
  Counter: Integer;

begin
  WriteLn('=== Pascal 匿名函数示例 ===');
  WriteLn;
  
  // 1. 基本匿名函数
  WriteLn('1. 基本匿名函数:');
  AddFunc := function(x, y: Integer): Integer
             begin
               Result := x + y;
             end;
             
  MultiplyFunc := function(x, y: Integer): Integer
                  begin
                    Result := x * y;
                  end;
  
  WriteLn('  3 + 4 = ', ApplyFunction(3, 4, AddFunc));
  WriteLn('  3 * 4 = ', ApplyFunction(3, 4, MultiplyFunc));
  WriteLn;
  
  // 2. 无参数匿名函数
  WriteLn('2. 无参数匿名函数:');
  Counter := 0;
  SimpleProc := procedure
                begin
                  Inc(Counter);
                  WriteLn('  匿名过程被执行，计数器: ', Counter);
                end;
                
  SimpleProc();
  SimpleProc();
  SimpleProc();
  WriteLn('  最终计数器值: ', Counter);
  WriteLn;
  
  // 3. 闭包 - 捕获外部变量
  WriteLn('3. 闭包示例:');
  Multiplier := GetMultiplier(10);
  WriteLn('  使用乘数10: 3 * 4 * 10 = ', Multiplier(3, 4));
  
  Multiplier := GetMultiplier(5);
  WriteLn('  使用乘数5: 3 * 4 * 5 = ', Multiplier(3, 4));
  WriteLn;
  
  // 4. 匿名函数与变量捕获
  WriteLn('4. 变量捕获:');
  Counter := 100;
  SimpleProc := procedure
                begin
                  WriteLn('  捕获的变量值: ', Counter);
                  Counter := Counter + 10;
                end;
                
  SimpleProc();
  SimpleProc();
  WriteLn('  修改后的变量值: ', Counter);
  WriteLn;
  
  WriteLn('匿名函数示例完成。');
  ReadLn;
end.